<?php
namespace app\index\model;

class Common{
    //
    public static function instance(){
        return new Common();
    }
    //
    public function getGlobalSet(){
        $tmp = db('global_set')->column('value', 'key');
        return $tmp;
    }
    //use by Order
    public function isOrderBlockIp($ip){
        $tmp = db('block_order_ip')->where('ip', '=', $ip)->value('boid', 0);
        return $tmp;
    }
    //use by Order
    public function getAdvert($aid, $field = '*'){
        $tmp = db('advert')->where('aid', '=', $aid)->field($field)->find();
        if($tmp){
            $tmp['url'] = isset($tmp['url']) ? trim($tmp['url']) : '';
            if($tmp['url'] != ''){
                substr($tmp['url'], 0, 4) === 'http' ? null : $tmp['url'] = 'http://'.$tmp['url'];
            }
        }
        return $tmp;
    }
    //use by Order
    public function getProductInfo($pidArr){
        $tmp = db('product')->where('pid', 'in', $pidArr)->column('cid,price,pname');
        $pn = [];
        $tp = $cid = 0;
        foreach($tmp as $row){
            $pn[] = $row['pname'];
            $tp = $tp + $row['price'];
            $cid = $cid == 0 ? $row['cid'] : $cid;
        }
        return ['pname'=>implode(' | ', $pn), 'price'=>$tp, 'cid'=>$cid];
    }
    //use by Order
    public function getOrderTplno($toid){
        $tmp = db('tpl_order')->where('toid', '=', $toid)->value('tono', '');
        return $tmp;
    }
    //
    public function postData($url, $data, $header = ''){
        if($url == '' || !is_array($data)){
            return false;
        }
        $ch = curl_init();
        if(!$ch){
            return false;
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        $header ? curl_setopt($ch, CURLOPT_HTTPHEADER, $header) : null;
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_USERAGENT, 'PHP Web Client/1.1.0 (john@example.com)');
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}